import XLSX from 'xlsx';

const createBook = () => XLSX.utils.book_new();

const createSheetForBook = (book, sheetProps) => {
  if (book) {
    const {
      name,
      data,
      opts = {},
      createSheet = XLSX.utils.aoa_to_sheet,
      handleSheet,
    } = sheetProps;
    const sheet = createSheet(data, opts);
    if (handleSheet) {
      handleSheet(sheet, { XLSX });
    }
    XLSX.utils.book_append_sheet(book, sheet, name);
    return sheet;
  }
  return null;
};

const getSheet = (book, sheetName) => book.Sheets[sheetName];

const saveBook = (book, filename = 'out.xlsx', writingOptions = {}) => {
  XLSX.writeFile(book, filename, writingOptions);
};

/*
[
  {
    name: 'Sheet1',
    data: [['S', 'h', 'e', 'e', 't'], ['1', '2', '3', '4', '5']],
  },
]
*/
const xlsxWriteFile = (data = [], filename, writingOptions) => {
  if (data.length) {
    const book = createBook();
    data.forEach(sheetProps => {
      createSheetForBook(book, sheetProps);
    });
    saveBook(book, filename, writingOptions);
  }
};

export { XLSX, createBook, createSheetForBook, getSheet, saveBook, xlsxWriteFile };
